var config = require('./config')
var userRouter = require('./routes/userRouter')
var shoppingRouter = require('./routes/shoppingRouter')
var express = require('express')
var path = require('path')
var bodyParser = require('body-parser')
// var { expressjwt } = require("express-jwt")
const expressjwt = require('express-jwt')
var app = express();

//导入并配置
const cors = require('cors')
// 将cors注册为全局中间件
app.use(cors())
// 静态资源托管
app.use('/public/', express.static(path.join(__dirname, 'public')));

// body-parser
app.use(bodyParser.urlencoded({ limit: '100mb', extended: true }));
app.use(bodyParser.json({ limit: '100mb' }));

// 注册将JWT字符串解析还原JSON对象的中间件就可以把用户信息挂载到req.user属性上
app.use(expressjwt({ secret: config.token.jwtSecretKey, algorithms: ['HS256'] }).unless({ path: [/^\/api\//] }))
app.use(userRouter)
app.use(shoppingRouter)

// 使用全局错误处理中间件捕获解析JWt失败后产生的错误
app.use((err, req, res, next) => {
  if (err.name == 'UnauthorizedError') {
    return res.send({ code: 401, msg: '无效token' })
  } else {
  }
  res.json({ code: 500, msg: '未知' })

})

app.listen(config.app.port, config.app.host, () => {
  console.log(`server is running at ${config.app.host}:${config.app.port}`);
})
